/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.edu.kamai.persistence.dao;

import com.edu.kamai.persistence.beans.PaperAnswer;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Session;
import org.hibernate.Transaction;

/**
 *
 * @author xyzhu
 */
public class PaperAnswerDao {
    private static final Log log = LogFactory.getLog(PaperAnswer.class);
    public static final String PAPERANSWER_BEAN = "com.edu.kamai.persistence.beans.PaperAnswer";
    private Session session = null;
    
    public PaperAnswerDao(){
        this.session  = kamaiHibernateUtil.getSessionFactory().openSession();
    }
    
    
    public void addPaperAnswer(PaperAnswer pa){
        log.debug("save paper answer instance");
        
        try{
            Transaction tx = session.beginTransaction();
            session.save(pa);
            tx.commit();
            log.debug("save successful");
        }catch(RuntimeException re){
            log.error("update failed",re);
            throw re;
        }
    }
    
    public PaperAnswer getPendingAnswerByID(int aid){
        log.debug("getting answer instance with aid: " + aid);
        try{
            PaperAnswer pa = (PaperAnswer)session.get(PAPERANSWER_BEAN, aid);
            return pa;
        }catch(RuntimeException re){
            log.error("get failed", re);
            throw re;
        }
    }
    
    public List<PaperAnswer> getPendingAnswer(){
        log.debug("check pending answer instance");
        try{
            Transaction tx = session.beginTransaction();
            String hqlStr=new String("from PaperAnswer where pending=0");
            List<PaperAnswer> pending = session.createQuery(hqlStr).list();
            return pending;
        }catch(Exception ex){
            log.error("check the pending list error",ex);
            return null;
        }
    }
    
    public void updateAnswerPaper(PaperAnswer pa){
        log.debug("update PaperAnswer instance");
        try{
            Transaction tx = session.beginTransaction();
            session.update(pa);
            tx.commit();
            log.debug("update successful");
            
        }catch(RuntimeException re){
            log.error("update failed",re);
            throw re;
        }
    }
    
    public List<PaperAnswer> getAnswerScoreByContestIDAndUserID(int cid,
            String uid){
        log.debug("get answer score instance");
        try{
            Transaction tx = session.beginTransaction();
            String hqlStr=new String("from PaperAnswer where contest_id="+cid + 
                    " and user_id='" + uid+"'");
            List<PaperAnswer> pending = session.createQuery(hqlStr).list();
            return pending;
        }catch(Exception ex){
            log.error("check the pending list error",ex);
            return null;
        }
        
    }
    
}
